package com.lobstar.xrpc.client.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lobstar.xrpc.common.po.SHeart;
import com.lobstar.xrpc.common.po.SMessage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class HeartBeatHandler extends SimpleChannelInboundHandler<SMessage>{

	private boolean online = false;
	private Logger logger = LoggerFactory.getLogger(getClass());
	private String id;

	public HeartBeatHandler(String id) {
		this.id = id;
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, SMessage msg) throws Exception {
		ctx.fireChannelRead(msg);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		logger.info("channel active");
		online = true;
		Channel channel = ctx.channel();
		channel.writeAndFlush(new SHeart(id,true));
		ctx.fireChannelActive();
	}

	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if(evt instanceof IdleStateEvent) {
			IdleStateEvent event = (IdleStateEvent) evt;
			if(event.state() == IdleState.ALL_IDLE) {
				ctx.channel().writeAndFlush(new SHeart(id));
			}
		}
		super.userEventTriggered(ctx, evt);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		super.channelInactive(ctx);
		online = false;
	}

}
